import { Commit } from 'vuex'
import { queryChatMessage } from '../../api/message'
import { queryUserNickname } from '../../api/user'

type ChatMessageItem = {
  id: number
  msgId: string
  msgType: string
  sender: number
  receiver: number
  avatar: string
  content: string
  sendTime: string
}

interface ChatMessageState {
  chatUserId: number
  chatMsgId: string
  chatNickname: string
  chatMessageList: ChatMessageItem[] | null
}

const chatMessageModule = {
  state: (): ChatMessageState => ({
    chatUserId: 0,
    chatMsgId: '',
    chatNickname: '',
    chatMessageList: null
  }),
  mutations: {
    SET_CHAT_USER_ID(state: ChatMessageState, userId: number) {
      state.chatUserId = userId
    },
    SET_CHAT_MSG_ID(state: ChatMessageState, msgId: string) {
      state.chatMsgId = msgId
    },
    SET_CHAT_NICKNAME(state: ChatMessageState, nickname: string) {
      state.chatNickname = nickname
    },
    SET_CHAT_MESSAGE_LIST(state: ChatMessageState, messageList: ChatMessageItem[]) {
      state.chatMessageList = messageList
    }
  },
  actions: {
    async GetChatNickname({ commit }: { commit: Commit }, chatUserId: number) {
      if (chatUserId !== 0) {
        try {
          const res = (await queryUserNickname(chatUserId)) as any
          if (res.code === 200 && res.data) {
            commit('SET_CHAT_NICKNAME', res.data.nickname)
          }
        } catch (err) {
          throw err
        }
      }
    },
    async GetChatMessageList({ commit }: { commit: Commit }, [chatUserId, userId]: number[]) {
      if (chatUserId !== 0) {
        try {
          const res = await queryChatMessage(userId, chatUserId)
          if (res.code === 200 && res.data) {
            commit('SET_CHAT_MSG_ID', res.data[0].msgId)
            commit('SET_CHAT_MESSAGE_LIST', res.data)
          }
        } catch (err) {
          throw err
        }
      }
    },
    FlushAllChatMessage({ commit }: { commit: Commit }) {
      commit('SET_CHAT_USER_ID', 0)
      commit('SET_CHAT_MSG_ID', '')
      commit('SET_CHAT_NICKNAME', '')
      commit('SET_CHAT_MESSAGE_LIST', null)
    }
  },
  getters: {
    getChatUserId: (state: ChatMessageState) => state.chatUserId,
    getChatMsgId: (state: ChatMessageState) => state.chatMsgId,
    getChatNickname: (state: ChatMessageState) => state.chatNickname,
    getChatMessageList: (state: ChatMessageState) => state.chatMessageList
  }
}

export default chatMessageModule
